<!-- eslint-disable vue/multi-word-component-names -->
<template>
<div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/rear-end/index' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>添加商品</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图区域 -->
<el-card>
    <!-- 提示区域    -->
    <el-alert title="添加商品信息" type="info" :closable="false" show-icon>
  </el-alert>
  <!-- 步骤条区域 -->
  <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
  <el-step title="基本信息"></el-step>
  <el-step title="商品参数"></el-step>
  <el-step title="商品属性"></el-step>
  <el-step title="商品图片"></el-step>
  <el-step title="商品内容"></el-step>
  <el-step title="完成"></el-step>
</el-steps>
<!-- tab区域  -->
<el-form :model="addForm" :rules="addFormRules"
 ref="addFormRef" label-width="100px" label-position="top">
<el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeLeave" @tab-click="tabClick">
    <el-tab-pane label="基本内容" name="0">
        <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="addForm.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
            <el-input v-model="addForm.goodsPrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goodsWeight">
            <el-input v-model="addForm.goodsWeight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goodsNumber">
            <el-input v-model="addForm.goodsNumber" type="number"></el-input>
        </el-form-item>
        <el-form-item lable="商品分类" prop="goodsCat">
            <!-- 级联选择框 -->
            <el-cascader
            class="bb"
            expand-trigger="hover"
            v-model="addForm.goodsCat"
            :options="catelist"
            :props="cateProps"
            @change="handleChange"></el-cascader>
            <el-alert
            class="aa"
            title="只能选择第二级，第一个分类作为主要分类"
            type="warning"
            :closable="false"
            show-icon
            effect="dark">
            </el-alert>
        </el-form-item>
    </el-tab-pane>
    <el-tab-pane label="商品参数" name="1">
        <!-- 渲染表单的item -->
        <el-form-item :label="item.attrName" v-for="(item,index) in manyTabeData" :key="item.attrId">
    <div :label="cb" v-for="(cb,i) in item.attrVals" :key="i" border  style="width: 100%;">
   <div style="width: 100%;border:1px solid #409eff;margin-top: 10px;min-height: 40px;display: flex; ">
    <span  v-if="item.urls[i]==='0'||item.urls[i]==='1'" style="min-width: 80px;margin-left: 2px;">
        {{cb}}
    </span>
    <span v-else >
        <!-- 动态参数项展示图片 -->
        <el-tooltip class="item" effect="dark" :content="cb" placement="bottom" >
       <img :src="'/api/rear-end/common/download?name='+item.urls[i]" alt=""  style="width: 80px;height: 30px;transform: translate(0%, 15%);">
      </el-tooltip>
    </span>
    <span style="margin-left: 10%;width: 30%;">
        <el-input type="number" size="mini" v-model="item.prices[i]" placeholder="请输入该商品增加多少钱" style="position: relative;top:-3px"></el-input>
    </span>
    <span  v-if="item.urls[i]==='0'||item.urls[i]==='1'" style="width: 80px;margin-left: 2px;">
          <!-- 添加动态参数项图片 -->
     <el-tooltip class="item" effect="dark" content="添加动态参数项图片" placement="bottom" >
      <i class="el-icon-plus "  style="float: right;margin-top: 12px;margin-right: 40px;" @click="showUploadDialog(i,item)"  ></i> 
      </el-tooltip>
    </span>
   </div>
</div>
    <!-- 输入文本框 -->
    <el-input
        class="input-new-tag"
        v-if="item.inputVisible"
        v-model="item.inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm(item,index)"
        @blur="handleInputConfirm(item,index)"
        >
    </el-input>
<!-- 添加按钮 -->
        <el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ New Tag</el-button>
  
        </el-form-item>
    </el-tab-pane>
    <el-tab-pane label="商品属性" name="2">
        <el-checkbox v-model="item.checked" v-for="item in onlyTableData" :key="item.attrId" style="width: 300px;">{{item.attrName}} <el-input v-model="item.attrVals" :disabled="!item.checked" ></el-input></el-checkbox>
    </el-tab-pane>
    <el-tab-pane label="商品图片" name="3">
        <el-upload
  class="upload-demo"
  :action="action"
  :headers="headerObj"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
 :on-success="handleSuccess"
  list-type="picture">
  <el-button size="small" type="primary">点击普通图片上传</el-button>
</el-upload>
<el-upload
  class="upload-demo"
  :action="action"
  :headers="headerObj"
  :on-remove="handleRemove1"
 :on-success="handleSuccess1"
  list-type="picture">
  <el-button size="small" type="primary">点击商品详情图片上传</el-button>
</el-upload>
    </el-tab-pane>
    <el-tab-pane label="商品内容" name="4">
        <quill-editor v-model="addForm.goodsIntroduce" ></quill-editor>
    <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
    </el-tab-pane>
  </el-tabs>
</el-form>
</el-card>
<el-dialog
  title="添加动态参数项图片"
  :visible.sync="addImgUrlDialogVisible"
  width="50%" @close="addImgUrlDialogClosed">
  <UploadVue ref="uploadRef" @img="img" :limit="1"></UploadVue>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addImgUrlDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addImgUrl">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="图片预览"
  :visible.sync="previewVisible"
  width="50%">
  <img :src="previewPath" alt="" style="width: 217px;height: 217px;">
</el-dialog>
</div>
</template>
<script>
import '@/assets/css/global.css'
import UploadVue from '@/components/rear-end/goods/Upload.vue'
import _ from 'lodash'
export default {
data(){return{
    activeIndex:'0',
    imgUrl:'',
    //添加商品表单
    addForm:{
        goodsName:'',
        goodsPrice:0,
        goodsWeight:0,
        goodsNumber:0,
        //商品分类
        goodsCat:[],
        //普通图片
        pics:[],
        //详情图片
        detailPics:[],
        //商品动态参数
        manyAttrs:[],
        //临时保存动态参数

        //商品静态属性
        onlyAttrs:[],
        //商品详情描述
        goodsIntroduce:''
    },
    addFormRules:{
        goodsName:[
        {required:true,message:'请输入商品名称',trigger:'blur'} 
        ],
        goodsPrice:[{required:true,message:'请输入商品价格',trigger:'blur'} ],
        goodsWeight:[{required:true,message:'请输入商品重量',trigger:'blur'} ],
        goodsNumber:[{required:true,message:'请输入商品数量',trigger:'blur'} ],
        goodsCat:[{required:true,message:'请输入商品分类',trigger:'blur'} ]
    },
    catelist:[],
    //级联选择框的配置对象
    cateProps:{
            value:'catId',
            label:'catName',
            children:'children',
            multiple: true, 
            
        },
        // 动态参数列表 
    manyTabeData:[],
    onlyTableData:[],
   addImgUrlDialogVisible:false,
   action:'/api/rear-end/common/upload',
   headerObj:{
          Authorization:localStorage.getItem("token")
        },
    previewPath:'',
    previewVisible:false,
    //第一次点击级联选择器的数据
    cat:[]
}},
components:{UploadVue},
created () {
    this.getCateList()
},
methods:{
      //获取所以分类列表
  async getCateList(){
        const res= await this.$api.rear_end.categories()
      if(res.data.code===1){
        this.catelist=res.data.data
    }else{
        this.$message.error(res.data.msg)
      }
    },
//级联选择框选中项变化，会触发这个函数
handleChange(){
        this.addForm.goodsCat = this.addForm.goodsCat.filter(item => item.length === 2)
        if(this.addForm.goodsCat.length===1){
        this.cat=this.addForm.goodsCat
        }
        if(this.addForm.goodsCat.length!==1&&this.addForm.goodsCat.length!==0){
            const index = this.addForm.goodsCat.findIndex((item) => item[1] === this.cat[1]);
    let  t= _.cloneDeep(this.addForm.goodsCat[0])
    this.addForm.goodsCat.splice(0,1,this.cat[0])
    this.addForm.goodsCat.splice(index,1,t)
        }
       
        return false
    },
    beforeLeave(activeName,oldActiveName){
if(oldActiveName==='0'&&this.addForm.goodsCat.length===0){
    this.$message.error('商品分类没有选')
    return false
}
    },
  async  tabClick(){
        if(this.activeIndex==='1'){
            const res=await this.$api.rear_end.attributes({sel:'many'},this.cateId)  
            if(res.data.code===1){
                res.data.data.forEach(item => {
                    item.attrVals= item.attrVals?item.attrVals.split(' '):[]
                    const price=[]
                    const url=[]
                    const checked=[]
                    item.attrVals.forEach(() => {
                        checked.push(false)
                        price.push('0')
                        url.push('0')
                   });
                    item.prices=price
                    item.urls=url
                    item.checkeds=checked
                     //控制文本框的显示和隐藏
                    item.inputVisible=false
                    item.inputValue=''
                });
                this.manyTabeData=res.data.data
            }else{
                this.$message.error('获取动态参数列表失败')
            }
        }else if(this.activeIndex==='2'){
           
            const res=await this.$api.rear_end.attributes({sel:'only'},this.cateId) 
            if(res.data.code===1){
                res.data.data.forEach(item => {
                    item.attrVals= item.attrVals?item.attrVals.split(' '):' '
               item.checked=false
                })
               this.onlyTableData=res.data.data
               console.log(this.onlyTableData)
         }
        }
    },
      // 点击打开添加图片对话框
    showUploadDialog(i,row){
       this.addImgUrlDialogVisible=true
       row.urls.splice(i,1,'1')  
    },
    img(val){
        this.imgUrl=val 
    },
    //保存添加动态参数项图片
  async  addImgUrl(){
      await  this.$refs.uploadRef.upload()
        this.manyTabeData.forEach(item=>{
            if(item.attrSel==='many'){
                item.urls.forEach(val=>{
                if(val==='1'||val===1){
                    this.b=true
                }})
     if(this.b){
      
        item.urls.splice(item.urls.indexOf('1'),1,this.imgUrl)
        this.imgUrl=''
        this.$refs.uploadRef.handleRemove()
                this.b=false
            }
            }
        })
 
        this.addImgUrlDialogVisible=false   
    },
    addImgUrlDialogClosed(){
        this.imgUrl=''
        this.$refs.uploadRef.handleRemove()
        this.manyTabeData.forEach(item=>{
            if(item.attrSel==='many'){
                item.urls.forEach(val=>{
                if(val==='1'||val===1){
                    this.b=true
                }})
     if(this.b){
        item.urls.splice(item.urls.indexOf('1'),1,'0')
                this.b=false
            }
            }
        })
        this.addImgUrlDialogVisible=false  
    },
 handlePreview(file){
      this.$api.rear_end.download(file.response.data).then(res=>{
        let url=window.URL.createObjectURL(new Blob([res.data], { type: 'image/jpeg' }))
        this.previewPath=url  
    })
    this.previewVisible=true
    },
    handleRemove(file){
        const i=this.addForm.pics.findIndex(x=>x===file.response.data)
        this.addForm.pics.splice(i,1)
    },
    handleSuccess(response){
this.addForm.pics.push(response.data)
    },
    handleRemove1(file){
        const i=this.addForm.detailPics.findIndex(x=>x===file.response.data)
        this.addForm.detailPics.splice(i,1)
    },
    handleSuccess1(response){
this.addForm.detailPics.push(response.data)
    },
    //添加商品
   add(){
        this.$refs.addFormRef.validate( async valid=>{
            if(!valid){
                this.$message.error('请填写必要表单项！')
                return 
            }
           const form= _.cloneDeep(this.addForm)
           for (let i = 0; i < form.goodsCat.length; i++) {
            form.goodsCat[i] = form.goodsCat[i].join(' ')
            }

            form.goodsCat=form.goodsCat.join(',')
            form.pics=form.pics.join(',')
            form.detailPics=form.detailPics.join(',')
            this.manyTabeData.forEach(item=>{
                const newInfo={
                    attrId:item.attrId,
                    attrName:item.attrName,
                    attrVals:item.attrVals.join(' '),
                    addPrice:item.prices.join(' '),
                    manyPics:item.urls.join(' '),
                    checkeds:item.checkeds.join(' ')
                }
                this.addForm.manyAttrs.push(newInfo)
            })
            this.onlyTableData.forEach(item=>{
                const newInfo={
                    attrId:item.attrId,
                    attrName:item.attrName,
                    attrVals:item.attrVals,
                    checkeds:item.checked
                }
                this.addForm.onlyAttrs.push(newInfo)
            })
           form.manyAttrs=this.addForm.manyAttrs
           form.onlyAttrs=this.addForm.onlyAttrs
         const res=await this.$api.rear_end.addGodds(form)
         if(res.data.code!==1){
            this.$message.error(res.data.msg)
         }
         else{
            this.$message.success("添加商品成功！")
            this.$router.push('/goods')
         }
        })
    },
     //控制按钮与文本框的切换显示
     showInput(row){
        row.inputVisible=true
        this.$nextTick(()=> {
          this.$refs.saveTagInput[0].focus()
        })
    },
    //文本框失去焦点或摁下enter都会触发
    handleInputConfirm(row){
        if(row.inputValue.trim().length===0){
            row.inputValue=''
            row.inputVisible=false
            return
        }
        row.attrVals.push(row.inputValue.trim())
        row.urls.push('0')
        row.prices.push(0)
        row.checkeds.push(true)
        row.inputValue=''
        row.inputVisible=false
    },
},
computed:{
    cateId(){
            if(this.addForm.goodsCat[0].length===2){
            return this.addForm.goodsCat[0][1]
        }else{
            return null
        }  
    }
}
}

</script>

<style  scoped lang="less">
.el-checkbox{
    margin: 0 10px 0 0 !important;
}
.upload-demo{
    margin: 5px 0;
}
.previewImg{
    width: 100%;
}
/deep/ .bb{
    float: left;
}
/deep/ .aa{
    float: left;  
margin-left: 20px;
width: 400px;
height: 40px;
}

</style>